package cn.lhx.blog.action;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import cn.lhx.blog.formbean.SystemFormbean;
import cn.lhx.blog.pojo.Archive;
import cn.lhx.blog.pojo.Article;
import cn.lhx.blog.pojo.ArticleCategory;
import cn.lhx.blog.pojo.Comment;
import cn.lhx.blog.service.ArtiCatgService;
import cn.lhx.blog.service.ArticleOrgService;
import cn.lhx.blog.service.ArticleService;
import cn.lhx.blog.service.CommentService;
import cn.lhx.blog.util.BlogInfo;
import cn.lhx.blog.util.PagenationTookit;

/**
 * 执行系统动作
 * 
 * @author lhx
 * 
 */
public class SystemAction extends DispatchAction {
	@Resource
	private ArtiCatgService artiCatgService;
	@Resource
	private ArticleOrgService articleOrgService;
	@Resource
	private ArticleService articleService;
	@Resource
	private CommentService commentService;

	/**
	 * 初始化博客，加载博客主页信息
	 * 
	 * @param mapping
	 * @param arg1
	 * @param request
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward init(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse arg3)
			throws Exception {
		HttpSession session=request.getSession();
		SystemFormbean sysf = (SystemFormbean) form;
		// 获取当前页码
		int page = sysf.getPage();
		page = page < 1 ? 1 : page;
		// 获得总共有多少篇日志
		long articleCount = articleService.statsArticleCount();
		// 计算出页数(pages)=articleCount/6
		int pages = PagenationTookit.getPages(BlogInfo.BLOGS_ONE_PAGE, articleCount);
		page = page > pages ? pages : page;
		log.info("page= " + page);
		request.setAttribute("pages", pages);
		request.setAttribute("curPage", page);
		// 设置页码导航条
		int nav[] = PagenationTookit.getPageNavigator(page,
				BlogInfo.COUNT_OF_PAGENUMBER_OF_MAINPAGE, pages);
		request.setAttribute("nav", nav);
		int base = page - 1;// 基点=第n页 -1
		// 读取几篇日志
		List<Article> articles = articleService.getArticles(base
				* BlogInfo.BLOGS_ONE_PAGE, BlogInfo.BLOGS_ONE_PAGE);
		session.setAttribute("articles", articles);
		// 读取最近回复
//		List<Comment> comments=commentService.getComments(0, 8);
//		session.setAttribute("comments", comments);
		//读取归档信息
		List<Archive> archives=articleService.getArchives();
		session.setAttribute("archives", archives);
		// 开始获取分类信息
//		List<ArticleCategory> artCatgList = artiCatgService.getAllCategory();
//		
//		session.setAttribute("categories", artCatgList);
		

		log.info("执行初始操作！即将进入博客主页面");
		return mapping.findForward("main_page3");
	}

}
